import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import { SDBody, SDLoading } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'

import GoodsClassify from '../../../comps/goods-classify'
import GoodsFilter from '../../../comps/goods-filter'
import GoodsSort from '../../../comps/goods-sort'
import GoodsItem from '../../../comps/goods-item'
import SKUPicker from '../../../comps/sku-picker'
import CommonEmptyView from '../../../comps/empty-view'

import ArrangePicIcon from '../../../images/ic_arrange_pic.png'
import ArrangeIcon from '../../../images/ic_arrange.png'
import SearchIcon from '../../../images/ic_search.png'
import PullDownNorIcon from '../../../images/ic_pulldown_nor.png'
import PullDownPreIcon from '../../../images/ic_pulldown_pre.png'
import CartIcon from '../../../images/ic_shopping_cart_small.png'
import EmptyIcon from '../../../images/ic_nothing_search.png'


import './index.less'

type PageState = {
  mainIsLoading: boolean,                 // 页面整体加载状态
  menuBarList: any[],                     // 菜单项
  displayType: 'arrangePic' | 'arrange',  // UI 展示风格
  classifyList: any[],                    // 分类数据列表
  filterList: any[],                      // 筛选数据列表
  sortList: any[],                        // 排序数据列表
  currentClassify: any,                   // 选中的分类
  currentFilter: any[],                   // 选中的筛选条件
  currentSort: any,                       // 选中的排序
  dataList: any[],                        // 商品数据列表
  loading: boolean,                       // 是否正在加载中
  hasData: boolean,                       // 是否有商品数据
  hasMore: boolean,                       // 是否有更多数据
  hideLoading: boolean,                   // 强制隐藏loading
}

type PageOwnProps = {}

interface TabBarGoodsPage {
  props: PageProps & PageOwnProps
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class TabBarGoodsPage extends Component<PageOwnProps, PageState> {

  constructor(args) {
    super(args)
    this.state = {
      menuBarList: [
        {
          title: '分类',
          selected: false,
          code: 'classify'
        }, {
          title: '筛选',
          selected: false,
          code: 'filter'
        }, {
          title: '排序',
          selected: false,
          code: 'sort'
        }
      ],
      displayType: 'arrangePic',
      mainIsLoading: true,
      classifyList: [],
      filterList: [],
      sortList: [],
      currentClassify: {},
      currentFilter: [],
      currentSort: {},
      dataList: [],
      loading: false,
      hasData: true,
      hasMore: true,
      hideLoading: false
    }
  }

  config: Config = {
    navigationBarTitleText: '商品列表',
    enablePullDownRefresh: true
  }

  componentDidMount () {
    this.fetchData(0, true, true)
  }

  onPullDownRefresh () {
    this.fetchData()
  }

  onReachBottom () {
    const { dataList } = this.state
    this.fetchData(dataList.length)
  }

  render () {
    const {
      menuBarList,
      displayType,
      mainIsLoading,
      loading,
      hasData,
      hasMore,
      hideLoading,
      dataList,
      classifyList,
      filterList,
      sortList
    } = this.state
    return (
      <SDBody sd-class='container' showPadding={false} loading={mainIsLoading}>
        <View className='menu-bar border-bottom_1px'>
          <View className='left'>
            {
              menuBarList.map((item, index) => {
                return <View className={`menu-item ${item.selected ? 'menu-item_sel' : ''}`} key={index} onClick={this.onMenuBarTaped.bind(this, index)}>
                  <View className="menu-title">{item.title}</View>
                  <Image className="menu-icon" src={item.selected ? PullDownPreIcon : PullDownNorIcon}></Image>
                </View>
              })
            }
          </View>
          <View className='right'>
            <View className="right-item" onClick={this.onSearchBtnTaped}>
              <Image className="right-icon" src={SearchIcon}></Image>
            </View>
            <View className="right-item" onClick={this.onDisplayTypeBtnTaped}>
              <Image className="right-icon" src={displayType == 'arrangePic' ? ArrangePicIcon : ArrangeIcon}></Image>
            </View>
          </View>
        </View>
        <View style='height:90rpx;'></View>
        <View className="main-content">
          {
            displayType == 'arrangePic' ? (
              <View className="cell-list-pic">
                {
                  dataList.map((item, index) => {
                    return (
                      <View className="cell-arrange-pic" key={index}>
                        <GoodsItem
                          extData={index}
                          width={336}
                          height={550}
                          imgUrl={item.coverImage || ''}
                          title={item.name}
                          price={SDUtils.formatPrice(`${item.minPrice}`)}
                          showTagPrice={true}
                          tagPrice={SDUtils.formatPrice(`${item.minTagPrice}`)}
                          showCartNum={false}
                          cartNum={0}
                          showSalesVolume={true}
                          salesVolume={item.salesVolume || 0}
                          showCartIcon={true}
                          bgColor='#fff'
                          onClick={this.gotoGoodsDetail}
                          onCartClick={this.onCartIconTaped}
                        />
                      </View>
                    )
                  })
                }
              </View>) : (
              <View className="cell-list">
                {
                  dataList.map((item, index) => {
                    return (
                      <View className="cell-arrange border-bottom_1px" key={index} onClick={this.gotoGoodsDetail.bind(this, index)}>
                        <View className="cell-left">
                          <Image className="cell-icon" src={item.coverImage || ''} mode='aspectFill' lazyLoad></Image>
                          {
                            item.cartNum ? (
                              <View className="cart-num-content">
                                <View className="title">9</View>
                              </View>
                            ) : null
                          }
                        </View>
                        <View className="cell-right">
                          <View className="cell-title">{item.name}</View>
                          <View className="cell-sub-title"></View>
                          <View className="cell-price">{SDUtils.formatPrice(`${item.minPrice}`)}</View>
                          <View className="cell-bottom">
                            <View className="cell-bitem">吊牌价：{SDUtils.formatPrice(`${item.minTagPrice}`)}</View>
                            <View className="cell-bitem">销量:{item.salesVolume || 0}</View>
                          </View>
                        </View>

                        <View className="cart-content" onClick={this.onCartIconTaped.bind(this, index)}>
                          <Image className="cart-icon" src={CartIcon}></Image>
                        </View>
                      </View>
                    )
                  })
                }

              </View>
            )
          }
        </View>
        <SDLoading loading={loading} hasMore={hasMore} hasData={hasData} hideLoading={hideLoading}>
          <CommonEmptyView title='暂无数据' icon={EmptyIcon} />
        </SDLoading>


        <GoodsClassify ref='compsClassify' dataList={classifyList} onDismiss={this.onClassifyCompsDismiss} onSelect={this.onClassifyCompsSelect} />
        <GoodsFilter ref='compsFilter' dataList={filterList} onDismiss={this.onFilterCompsDismiss} onSelect={this.onFilterCompsSelect} />
        <GoodsSort ref='compsSort' dataList={sortList} onDismiss={this.onSortCompsDismiss} onSelect={this.onSortCompsSelect} />
        <SKUPicker ref='compsSkuPicker' onSelect={this.onSkuSelect}/>
      </SDBody>
    )
  }

  fetchData = async (offset: number = 0, resetDataList: boolean = false, fetchCondition: boolean = false) => {
    let {
      classifyList,
      filterList,
      sortList,
      dataList,
      hasData,
      hasMore,
      loading,
      currentClassify,
      currentSort,
      currentFilter
    } = this.state

    // 没有更多或者正在加载中，不请求网络
    if (loading || (offset > 0 && !hasMore)) { return }
    if (offset == 0) {
      dataList = []
    }
    let pageState: any = {
      loading: true,
      hasMore: true,
      hasData: true,
      hideLoading: resetDataList,
    }
    if (resetDataList) {
      pageState.dataList = dataList
    }
    await this.setState({...pageState})

    try {
      if (fetchCondition) {
        classifyList = []
        let categoryTree = await SDUtils.doGet('/wxmini/catalog/tree?traderId=1')
        for (let i = 0; i < categoryTree.length; i++) {
          let categoryItem = categoryTree[i]
          if (i == 0) {
            classifyList.push({
              catalogId: '',
              code: '',
              name: '全部',
              children: [
                {
                  parentId: '',
                  catalogId: '',
                  code: '',
                  name: '全部'
                }
              ]
            })
          }
          let categoryItemChildrenList = (categoryItem.children || []).map(item => {
            return {
              parentId: categoryItem.catalogId,
              catalogId: item.catalogId,
              code: item.code,
              name: item.name
            }
          })
          categoryItemChildrenList.unshift({
            parentId: categoryItem.catalogId,
            catalogId: categoryItem.catalogId,
            code: categoryItem.code,
            name: '全部'
          })
          categoryItem = {
            catalogId: categoryItem.catalogId,
            code: categoryItem.code,
            name: categoryItem.name,
            children: categoryItemChildrenList
          }
          classifyList.push(categoryItem)
        }
        filterList = await SDUtils.doGet('/wxmini/search?traderId=1')
        sortList = [
          {
            title: '综合排序',
            code: 'SYNTHESIS'
          }, {
            title: '价格从高到低',
            code: 'PRICE_DESC'
          }, {
            title: '价格从低到高',
            code: 'PRICE_ASC'
          }, {
            title: '销量从高到低',
            code: 'SALE_VOLUME_DESC'
          }, {
            title: '销量从低到高',
            code: 'SALE_VOLUME_ASC'
          }
        ]

        currentClassify = {}
        currentFilter = []
        currentSort = {}
      }

      let param: any = {
        offset: offset,
        limit: 20,
        sortType: 'SYNTHESIS',
        traderId: '1'
      }
      if (currentClassify && currentClassify.catalogId) {
        param.catalogId = currentClassify.catalogId
      }
      if (currentFilter && currentFilter.length > 0) {
        for (let i = 0; i < currentFilter.length; i++) {
          let sectionItem = currentFilter[i]
          let code = sectionItem.code
          let cellList = (sectionItem.items || []).filter(item => item.selected && item.title != '不限')
          if (cellList.length > 0) {
            let str = ''
            for (let j = 0; j < cellList.length; j++) {
              str += `${cellList[j].title},`
            }
            if (str.length > 0) {
              str = str.substr(0, str.length - 1)
            }
            if (str.length > 0) {
              param[code] = str
            }
          }

        }
      }
      if (currentSort && currentSort.code) {
        param.sortType = currentSort.code
      }

      const goodsResp = await SDUtils.doGet(`/wxmini/traderProduct`, {
        ...param
      })
      hasData = goodsResp.total > 0
      dataList = dataList.concat(goodsResp.items || [])
      hasMore = goodsResp.total > dataList.length

    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      Taro.stopPullDownRefresh()
      this.setState({
        dataList: dataList,
        hasMore: hasMore,
        hasData: hasData,
        mainIsLoading: false,
        loading: false,
        classifyList: classifyList,
        filterList: filterList,
        sortList: sortList,
        currentClassify: currentClassify,
        currentFilter: currentFilter,
        currentSort: currentSort,
        hideLoading: false
      })
    }
  }

  _togglePopup = (tapedItem) => {
    const { menuBarList, currentClassify, currentSort, currentFilter } = this.state
    const selectedMenuBar = menuBarList.find(item => item.selected) || tapedItem
    const code = selectedMenuBar.code
    if (!code) { return }
    let param: object = {}
    let comps: any = undefined
    if (code == 'classify') {
      this.refs.compsFilter && this.refs.compsFilter.dismiss()
      this.refs.compsSort && this.refs.compsSort.dismiss()
      comps = this.refs.compsClassify
      param = currentClassify
    } else if (code == 'filter') {
      this.refs.compsClassify && this.refs.compsClassify.dismiss()
      this.refs.compsSort && this.refs.compsSort.dismiss()
      comps = this.refs.compsFilter
      param = currentFilter
    } else {
      this.refs.compsClassify && this.refs.compsClassify.dismiss()
      this.refs.compsFilter && this.refs.compsFilter.dismiss()
      comps = this.refs.compsSort
      param = currentSort
    }
    if (comps) {
      selectedMenuBar.selected ? comps.show(param) : comps.dismiss()
    }
  }

  onMenuBarTaped = (index: number) => {
    let { menuBarList } = this.state
    menuBarList = menuBarList.map((item, idx) => {
      if (idx != index) {
        item.selected = false
      }
      return item
    })
    menuBarList[index].selected = !menuBarList[index].selected
    this.setState({
      menuBarList: menuBarList
    }, () => {
      // 展示
      this._togglePopup(menuBarList[index])
    })
  }

  onSearchBtnTaped = () => {
    SDUtils.jumpTo('/pages/goods/search/index')
  }

  onDisplayTypeBtnTaped = () => {
    let displayType = this.state.displayType
    this.setState({
      displayType: displayType == 'arrange' ? 'arrangePic' : 'arrange'
    })
  }

  onClassifyCompsSelect = (currentClassify: any) => {
    this.setState({
      currentClassify: currentClassify
    }, () => {
      this.fetchData(0, true)
    })
    this.refs.compsClassify && this.refs.compsClassify.dismiss()
  }

  onClassifyCompsDismiss = () => {
    let { menuBarList } = this.state
    menuBarList = menuBarList.map(item => {
      if (item.code == 'classify') {
        item.selected = false
      }
      return item
    })
    this.setState({
      menuBarList: menuBarList
    })
  }

  onFilterCompsSelect = (currentFilter: any[]) => {
    this.setState({
      currentFilter: currentFilter
    }, () => {
      this.fetchData(0, true)
    })
    this.refs.compsFilter && this.refs.compsFilter.dismiss()
  }

  onFilterCompsDismiss = () => {
    let { menuBarList } = this.state
    menuBarList = menuBarList.map(item => {
      if (item.code == 'filter') {
        item.selected = false
      }
      return item
    })
    this.setState({
      menuBarList: menuBarList
    })
  }

  onSortCompsSelect = (currentSort: any) => {
    this.setState({
      currentSort: currentSort
    }, () => {
      this.fetchData(0, true)
    })
    this.refs.compsSort && this.refs.compsSort.dismiss()
  }

  onSortCompsDismiss = () => {
    let { menuBarList } = this.state
    menuBarList = menuBarList.map(item => {
      if (item.code == 'sort') {
        item.selected = false
      }
      return item
    })
    this.setState({
      menuBarList: menuBarList
    })
  }

  onSkuSelect = () => {
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.dismiss()
  }

  onCartIconTaped = (index: number, e) => {
    e.stopPropagation && e.stopPropagation()
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    this.refs.compsSkuPicker && this.refs.compsSkuPicker.show(productId)
  }

  gotoGoodsDetail = (index: number) => {
    const { dataList } = this.state
    let productId = dataList[index].productId
    if (!productId) {
      SDUtils.showMsg('商品ID错误')
      return
    }
    SDUtils.jumpTo('/pages/goods/detail/index', { productId: productId})
  }

}

export default TabBarGoodsPage as ComponentClass<PageOwnProps, PageState>
